package org.breathe.command.impl.selector;

import org.breathe.command.Command;
import org.breathe.command.CommandType;
import org.breathe.protocal.Resp;
import org.breathe.protocal.decode.BulkString;
import org.breathe.protocal.decode.Errors;
import org.breathe.protocal.decode.RespInteger;
import org.breathe.server.core.RedisCore;

/**
 * @author: breathe
 * @createTime: 2025-06-08
 */
public class Select implements Command {

    private RedisCore redisCore;
    private int dbIndex;

    public Select(RedisCore redisCore) {
        this.redisCore = redisCore;
    }
    @Override
    public CommandType getType() {
        return CommandType.SELECT;
    }

    @Override
    public void setContext(Resp[] array) {
        if (array.length == 2) {
            dbIndex = Integer.parseInt(((BulkString)array[1]).getContent().getString());
        } else {
            throw new IllegalArgumentException("argument fail");
        }
    }

    @Override
    public Resp handle() {
        try {
            redisCore.selectDB(dbIndex);
            return new RespInteger(1);
        } catch (Exception e) {
            return new Errors("argument fail");
        }
    }

    @Override
    public boolean writeCommand() {
        return true;
    }
}
